// pages/sticker_detail/sticker_detail.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    collection: "/images/ico_collect.svg",
    status: 0, //收藏状态 1已收藏 0未收藏 notLogin未登录
    stickerDetail: [],
    dataTips: '',
    stickerid: '',
    forwardImgUrl: '/images/tukaxiu_logo.png',
    userToken: '',
    cllectionTxt:'收藏'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    var stickerid = options.stickerid; //获取上个页面的表情ID
    this.setData({
      stickerid: options.stickerid
    })
    var userToken = wx.getStorageSync('loginToken');
    this.setData({
      userToken: userToken
    });
    console.log('读取缓存TOKEN：' + userToken);
    wx.request({
      url: app.globalData.stickerDtaileUrl + stickerid + '/' + userToken, //接口地址
      data: {},
      method: 'GET',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        console.log('页面收藏状态:' + res.data.data.is_coll)
        if (res.data.data.is_coll == 0) {
          that.setData({
            status: 0,
            collection: "/images/ico_collect.svg",
            cllectionTxt: '收藏'
          });
        } else if (res.data.data.is_coll == 1) {
          that.setData({
            status: 1, //收藏状态 1已收藏 0未收藏 notLogin未登录
            collection: "/images/ico_collected.svg",
            cllectionTxt: '已收藏'
          });
        };
        var imgList = [];
        imgList.push(res.data.data);
        // console.log(imgList);
        // console.log(res.data.xiangs);
        if (res.data.xiangs.length == 0) {
          console.log("没得数据");
          that.setData({
            dataTips: "也许这个太冷门了吧 O.O",
            hide: "true"
          })
        } else {
          that.setData({
            hide: "false"
          })
        };
        that.setData({
          stickerDetail: imgList,
          stickerLists: res.data.xiangs,
          forwardImgUrl: res.data.data.img
        })

      },
      fail: function() {
        that.setData({
          dataTips: "获取数据失败"
        })
      }
    });
    //获取收藏状态
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    wx.showShareMenu({
      withShareTicket: true
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  previewImage: function(e) {
    var that = this;
    var current = e.target.dataset.src;
    var imgSrcList = this.data.stickerDetail
    wx.previewImage({
      current: current,
      urls: [current]
      //urls: imgSrcList
    })
  },
  //收藏表情
  collectImg: function(e) {
    var that = this;
    var statusValue = e.currentTarget.dataset.status; //表情收藏状态
    var token = wx.getStorageSync('loginToken');
    var stickerid = this.data.stickerid;
    // console.log('缓存的token:' + token);
    if (statusValue == 1) { //已收藏
      console.log('请求已收藏');
      wx.request({
        url: app.globalData.unCollectUrl,
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        data: {
          token: token,
          imgid: stickerid,
        },
        success: function(res) {
          console.log('返回的信息：' + res.data);
          if (res.statusCode == 200) {
            that.setData({
                collection: "/images/ico_collect.svg",
                routeY: "",
                cllectionTxt: '收藏',
                status: 0
              }),
              wx.showToast({
                title: '取消收藏',
                icon: 'none',
                duration: 500
              })
          } else {
            wx.showToast({
              title: '取消收藏失败',
              icon: 'none',
              duration: 500
            })
          }
        },
        fail: function() {
          console.log('收藏请求失败')
        }
      })
    } else if (statusValue == 0) {
      console.log('请求未收藏');
      var userToken = wx.getStorageSync('loginToken');
      if (token != '') {
        wx.request({
          url: app.globalData.collectUrl,
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          method: "POST",
          data: {
            token: userToken,
            imgid: stickerid,
          },
          success: function(res) {
            console.log('返回的信息1：' + res.data);
            if (res.statusCode == 200) {
              that.setData({
                  collection: "/images/ico_collected.svg",
                  routeY: "routeY",
                  status: 1,
                  cllectionTxt: '已收藏'
                }),
                wx.showToast({
                  title: '已收藏',
                  icon: 'none',
                  duration: 500
                })
            } else if (res.statusCode == 302) {
              console.log('重新取token');
              wx.showToast({
                title: '登录成功',
                icon: 'warn',
              });
              app.wxLogin();
            } else if (res.statusCode == 500) {
              wx.showToast({
                title: '表情已存在',
                icon: 'none',
                duration: 500
              });
              that.setData({
                collection: "/images/ico_collected.svg",
                routeY: "routeY",
                status: 1,
                cllectionTxt: '已收藏'
              });
            }
          },
          fail: function() {
            console.log('收藏请求失败')
          }
        });
      } else {
        //无token
        console.log('缓存中没有token');
        app.wxLogin();
        // var token = wx.getStorageSync('loginToken');
        console.log('userToken:' + token);
        wx.request({
          url: app.globalData.collectUrl,
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          method: "POST",
          data: {
            token: token,
            imgid: stickerid,
          },
          success: function(res) {
            console.log('返回的信息1：' + res.data);
            if (res.statusCode == 200) {
              that.setData({
                  collection: "/images/ico_collected.svg",
                  routeY: "routeY",
                  status: 1
                }),
                wx.showToast({
                  title: '已收藏',
                  icon: 'success',
                  duration: 500
                })
            } else if (res.statusCode == 500) {
              wx.showToast({
                title: '表情已存在',
                icon: 'none',
                duration: 500
              });
              that.setData({
                collection: "/images/ico_collected.svg",
                routeY: "routeY",
                status: 1
              });
            }
          },
          fail: function() {
            console.log('收藏请求失败')
          }
        });
      };
      //获取用户信息存到全局数据中
      wx.getSetting({
        success: res => {
          if (res.authSetting['scope.userInfo']) {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
            wx.getUserInfo({
              success: res => {
                // 可以将 res 发送给后台解码出 unionId
                app.globalData.userInfo = res.userInfo
                console.log(res.userInfo);
                // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                // 所以此处加入 callback 以防止这种情况
                if (this.userInfoReadyCallback) {
                  this.userInfoReadyCallback(res)
                }
              },
              fail: res => {
                console.log('获取用户信息失败')
              }
            })
          }
        }
      });
    }
  },
  onShareAppMessage: function(res) {
    var that = this;
    var stickerid = this.data.stickerid;
    console.log('转发' + stickerid);
    if (res.from === 'button') {
      // 来自页面内转发按钮
      //console.log(res.target)
    }
    return {
      title: '你的朋友给你发了一个表情',
      path: 'pages/sticker_detail/sticker_detail?stickerid=' + stickerid,
      imageUrl: this.data.forwardImgUrl
    }
  },
  //查看表情详细
  toStickerDetail: function(e) {
    var that = this;
    var stickerid = e.currentTarget.dataset.stickerid;
    this.setData({
      stickerid: stickerid
    })
    wx.navigateTo({
      url: '../sticker_detail/sticker_detail?stickerid=' + stickerid,
    })
  },
  //查看tips
  toTips: function(e) {
    wx.navigateTo({
      url: '../tips/tips'
    })
  },
  //保存图片到相册
  saveStickerToPhotosAlbum: function() {
    var that = this;
    wx.getSetting({
      //授权访问相册
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              console.log('授权访问相册成功')
            }
          })
        }
      }
    });
    wx.showToast({
      title: '保存中',
      icon: 'loading'
    });
    wx.downloadFile({
      url: this.data.forwardImgUrl,
      success(res) {
        if (res.statusCode == 200) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: function(res) {
              wx.showToast({
                title: '保存图片成功！',
                icon: 'success',
                duration: 1000
              })
            },
            fail: function(res) {
              console.log('保存相册失败');
            }
          })
        }
      },
      fail: function(res) {
        console.log('下载失败');
      }
    })
  },
  //首页
  toIndex: function (e) {
    console.log('回到首页');
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

})